package com.byt.framlib.basemvp.interceptor;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;

import com.byt.framlib.base.BaseConst;
import com.byt.framlib.commonutils.SharePerUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 类名称：  RequestHeaderIntercept
 * 创建者：  钟文浩
 * 类描述：  Retrofit拦截器，用于添加请求头信息
 */
public class RequestHeaderIntercept implements Interceptor {

    private static RequestHeaderIntercept instance = null;

    private RequestHeaderIntercept() {
    }

    public static RequestHeaderIntercept getInstance() {
        if (instance == null) {
            synchronized (RequestHeaderIntercept.class) {
                if (instance == null) {
                    instance = new RequestHeaderIntercept();
                }
            }
        }
        return instance;
    }

    @TargetApi(Build.VERSION_CODES.O)
    @Override
    public Response intercept(Chain chain) throws IOException {
        String token = SharePerUtils.getSharedString(BaseConst.USER_TOKEN);
        Request.Builder request = chain.request().newBuilder();
        if (!TextUtils.isEmpty(token)) {
//            int radomcode = millions(1, 999999999);
//            long ts = System.currentTimeMillis();
//            String Md5Token = MD5Security.getMd5_32(token + ":" + ts + ":" + radomcode).toLowerCase();
//            head = Base64.getEncoder().encodeToString((token + ":" + Md5Token).getBytes("UTF-8"));
//            request.addHeader("Authorization", "Basic " + head);
//            request.addHeader("in", radomcode + "");
            request.addHeader("Token", token);
        }
        request.addHeader("Content-Type", "application/json");
        return chain.proceed(request.build());
    }

    private int millions(int min, int size) {
        int times = (int) (min + Math.random() * (size));
        return times;
    }
}